import {
	Button,
	Form,
	Row,
	Col,
	Input,
	Select,
	message,
	DatePicker,
	InputNumber,
} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import React, {useState, useEffect, useRef} from 'react'
import {connect, history} from 'umi'
import moment from 'moment'
import {ArrowDownOutlined} from '@ant-design/icons'
import styles from './index.less'
import Modal from '@/components/Modal'
import {getAllParking} from '@/service/storage/archives'
import CustomTable from '@/components/Table'
import {
	addParkingfeesettlement,
	editParkingfeesettlement,
	editParkingfeesettlementSubmit,
	getCarModelList,
	getCostTypeList,
	getVehicleCostStatisticsList,
	parkingfeesettlementInfo,
} from '@/service/storage/parkingLot'
import {
	completeTask,
	deleteProcessInstance,
	processRecordSave,
} from '@/service/common'
import Examine from '@/components/Examine'
import {downloadDocumentUrl} from '@/service/common/download'
import OperationRecord from '@/components/OperationRecord'

type DataType = {
	warehouseName: string | string[] | null
	startUpStatus: number
	id: string
	supplierCode: string
	supplierName: string
	serviceType: string
	contacts: string
	status: string
	date: string
}

const add = (props: any) => {
	const {query} = props.location
	const [form] = Form.useForm()
	const [costForm] = Form.useForm()
	const [type, setType] = useState<string>()
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [formData, setFormData] = useState<any>({})
	const [dataSource, setDataSource] = useState<DataType[]>([])
	const [motorcycleType, setMotorcycleType] = useState<any[]>([])
	const [warehouse, setWarehouse] = useState<any>()
	const [carModel, setCarModel] = useState<any>() // 车型
	const [costData, setCostData] = useState<any>({})
	const [allData, setAllData] = useState<any>({})
	const [mouth, setMouth] = useState<any>()
	const [warehouseData, setWarehouseData] = useState<any>([])

	const examineRef = useRef<any>(null)
	const [saveType, setSaveType] = useState(false)
	const [examineType, setExamineType] = useState<string>('')
	const [btnLoading, setBtnLoading] = useState(false)
	const [isExamineModalOpen, setIsExamineModalOpen] = useState(false)
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	const getData = (data: any) => {
		setLoading(true)
		getVehicleCostStatisticsList({...params, ...data})
			.then((res: any) => {
				if (res?.success) {
					setDataSource(res.data?.records)
					setTotal(res?.data?.total)
					if (res?.data?.total !== 0) {
						costForm.setFieldsValue({
							totalAmount: res.data?.records?.[0]?.totalPrice,
						})
					}
				}
				setLoading(false)
			})
			.catch(() => {
				setDataSource([])
				setLoading(false)
			})
	}

	useEffect(() => {
		if (carModel && mouth && costData?.costType) {
			getData({
				...costData,
				warehouseArchivesId:
					warehouse?.id || allData?.warehouseArchivesId,
				carModel,
				settlementMonth: mouth,
			})
		} else {
			setDataSource([])
		}
	}, [params, warehouse, carModel, costData, mouth])
	// 根据路由判断当前页面状态
	useEffect(() => {
		/** 获取停车场列表 */
		getAllParking({warehouseType: 1})
			.then((res: any) => {
				setWarehouseData(res.data)
			})
			.catch(() => {
				setWarehouseData([])
			})
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else if (hrefs.includes('add')) {
			setType('add')
		} else if (hrefs.includes('edit')) {
			setType('edit')
		} else {
			setType('examine')
		}
	}, [])

	const getCarModelData = (warehouseId: string) => {
		getCarModelList({warehouseId})
			.then((res: any) => {
				const newData = res?.data?.map((item: any) => ({
					value: item,
					label: item,
				}))
				setMotorcycleType(newData)
			})
			.catch((err) => {
				setMotorcycleType([])
				message.error(err)
			})
	}
	const getCostTypeData = (archivesId: string, settlementMonth: string) => {
		getCostTypeList({
			archivesId,
			settlementMonth: moment(settlementMonth).format('YYYY-MM'),
		})
			.then((res: any) => {
				if (res.success) {
					if (res?.data?.costType) {
						setCostData(res.data)
						form.setFieldsValue({
							costType:
								res?.data?.costType === '1'
									? '按车位'
									: '按月固定租金',
						})
					} else {
						setCostData({})
						form.setFieldsValue({
							costType: undefined,
						})
						message.warning('所选仓库暂无结算模式')
					}
				} else {
					form.setFieldsValue({costType: undefined})
				}
			})
			.catch((err) => {
				setCostData({})
				message.error(err)
			})
	}

	// 获取仓库内车型数据和结算模式
	useEffect(() => {
		if (warehouse) {
			form.setFieldsValue({carModel: undefined})

			getCarModelData(warehouse?.id)
		}
	}, [warehouse])
	useEffect(() => {
		if (warehouse && mouth) {
			getCostTypeData(warehouse?.id, mouth)
		}
	}, [warehouse, mouth])

	useEffect(() => {
		if (query?.id) {
			parkingfeesettlementInfo(query?.id).then((res: any) => {
				if (res?.data) {
					setAllData(res.data)
					setCarModel(res?.data?.carModel)
					setDataSource(res?.data?.carConstList)
					getCarModelData(res?.data?.warehouseArchivesId)
					setWarehouse({id: res?.data?.warehouseArchivesId})
					getCostTypeData(
						res?.data?.warehouseArchivesId,
						moment(res?.data?.settlementMonth).format('YYYY-MM'),
					)
					setMouth(
						moment(res?.data?.settlementMonth).format('YYYY-MM-DD'),
					)
					form.setFieldsValue({
						...res.data,
						settlementMonth: moment(res?.data?.settlementMonth),
						costType:
							res?.data?.costType === '1'
								? '按车位'
								: '按月固定租金',
					})
					costForm.setFieldsValue({
						...res.data,
					})
				}
			})
		}
	}, [query])

	const onSave = async (types: string) => {
		const value = await form.validateFields()
		const costValue = await costForm.validateFields()
		if (value && costValue) {
			if (dataSource?.length) {
				setFormData({
					...value,
					...costValue,
					costType: value?.costType === '按车位' ? '1' : '2',
					settlementMonth: moment(value?.settlementMonth).format(
						'YYYY-MM-DD',
					),
					carConstList: dataSource,
					auditResult: types === 'save' ? 1 : 2,
				})
				setIsModalOpen(true)
			}
		} else {
			message.warning('所选条件下没有车辆，无法生成费用结算')
		}
	}

	const onSubmit = () => {
		let request: any
		if (query?.id) {
			// 编辑
			request = editParkingfeesettlement({...formData, id: query.id})
		} else {
			request = addParkingfeesettlement(formData)
		}
		request
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}
	const onModify = async (status: number) => {
		const value = await costForm.validateFields()
		const queryData: any = {
			actualAmount: value?.actualAmount,
			id: query.id,
			auditUser: `${allData?.auditUser},${props?.user?.userId}`,
			auditUserName: `${allData?.auditUserName},${props?.user?.userName}`,
		}
		if (status !== 1) {
			queryData.auditResult = examineType === '同意' ? 4 : 3
		}
		editParkingfeesettlementSubmit(queryData)
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}

	const columns: ColumnsType<DataType> = [
		{
			title: '车牌号',
			dataIndex: 'carNo',
			align: 'center',
			width: 100,
		},
		{
			title: '车架号',
			dataIndex: 'carFrameNo',
			align: 'center',
			width: 150,
		},
		{
			title: '车型',
			dataIndex: 'carModel',
			align: 'center',
			width: 150,
		},
		{
			title: '时间范围内累积天数',
			dataIndex: 'carDays',
			align: 'center',
			width: 180,
		},
		{
			title: '系统计算应付费用',
			dataIndex: 'cost',
			align: 'center',
			width: 150,
		},
	]
	/** 审核 */
	const onCompleteTask = async () => {
		setBtnLoading(true)
		const examineData = await examineRef.current.getData()
		const userId = props?.user?.userId
		let request
		if (examineType === '拒绝') {
			request = deleteProcessInstance({
				processId: query?.processInstanceId,
				reason: JSON.stringify({
					url: examineData?.url,
					message: examineData?.message,
					userId: userId.toString(),
				}),
			})
		} else {
			request = completeTask({
				reviewerId: userId.toString(),
				processInstanceId: query?.processInstanceId,
				pass: examineType === '同意' ? 1 : 2,
				...examineData,
			})
		}
		request
			.then((res: any) => {
				if (res?.success) {
					if (examineType === '拒绝') {
						processRecordSave({
							bizType: 9,
							bizNo: query?.id,
							processId: query?.processInstanceId,
						})
					}
					onModify(res?.data?.processStatus)
				} else {
					setBtnLoading(false)
				}
			})
			.catch((err) => {
				message.error(err)
				setBtnLoading(false)
			})
	}
	return (
		<div className={styles.add}>
			{(type === 'examine' || type === 'view') &&
			query?.processInstanceId ? (
				<Examine
					ref={examineRef}
					examineType={type === 'examine'}
					orgId={props?.user?.orgId}
					processInstanceId={query?.processInstanceId}
					bizType={9}
					bizNo={query?.id}
				/>
			) : (
				''
			)}
			<Form
				form={form}
				name="basic"
				layout="horizontal"
				labelCol={{flex: '100px'}}
				labelAlign="right"
				labelWrap
				autoComplete="off"
				disabled={type === 'view' || type === 'examine'}>
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="仓库"
							name="warehouseArchivesId"
							rules={[{required: true}]}>
							<Select
								showSearch
								placeholder="请选择"
								allowClear
								fieldNames={{
									value: 'id',
									label: 'warehouseName',
								}}
								optionFilterProp="warehouseName"
								onChange={(value: any, key: any) => {
									setDataSource([])
									if (key) {
										setWarehouse(key)
									} else {
										setWarehouse({})
									}
									setCarModel(undefined)
								}}
								options={warehouseData}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="结算月份"
							name="settlementMonth"
							rules={[{required: true}]}>
							<DatePicker
								picker="month"
								onChange={(value) => {
									setCostData({})
									setTotal(undefined)
									setParams({
										current: 1,
										size: 10,
									})
									setMouth(moment(value).format('YYYY-MM-DD'))
									costForm.setFieldsValue({
										totalAmount: '-',
									})
								}}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="结算模式"
							name="costType"
							rules={[{required: true}]}>
							<Input
								placeholder="根据所选仓库及结算月份带出"
								disabled
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="车型"
							name="carModel"
							rules={[{required: true}]}>
							<Select
								placeholder="请选择"
								allowClear
								options={motorcycleType}
								onSelect={(value: any) => {
									setCarModel(value)
								}}
							/>
						</Form.Item>
					</Col>
				</Row>
			</Form>
			<div className={styles.btnlist}>
				{type === 'view' ? (
					<Button
						icon={<ArrowDownOutlined />}
						className={styles.import}
						ghost
						size="small"
						onClick={() => {
							downloadDocumentUrl({
								resourceId: '140',
								queryDesc:
									'停车场-停车场费用结算-编辑,resourceId:140',
								queryParam: {settlementId: query?.id},
							})
						}}>
						导出
					</Button>
				) : (
					''
				)}
			</div>
			<CustomTable
				params={params}
				columns={columns}
				total={total}
				pagination
				callback={(pagination: any) => {
					setParams(pagination)
				}}
				loading={loading}
				dataSource={dataSource}
			/>
			<Form
				form={costForm}
				name="basic"
				layout="horizontal"
				labelCol={{flex: '140px'}}
				labelAlign="right"
				labelWrap
				autoComplete="off"
				disabled={type === 'view'}>
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item label="系统计算合计费用" name="totalAmount">
							<Input placeholder="请输入" disabled />
						</Form.Item>
					</Col>
					{type === 'view' || type === 'examine' ? (
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="实际费用"
								name="actualAmount"
								rules={[{required: true}]}>
								<InputNumber
									max={1000000000}
									placeholder="请输入"
								/>
							</Form.Item>
						</Col>
					) : (
						''
					)}
				</Row>
			</Form>
			{type === 'view' ? (
				<>
					<div className={styles.title}>操作记录</div>
					<OperationRecord businessId={query?.id} businessType={39} />
				</>
			) : (
				''
			)}
			<div className={styles.wrap}>
				{type === 'examine' ? (
					<>
						<Button
							type="primary"
							htmlType="submit"
							onClick={() => {
								setExamineType('同意')
								setIsExamineModalOpen(true)
							}}>
							同意
						</Button>
						<Button
							onClick={() => {
								setExamineType('驳回')
								setIsExamineModalOpen(true)
							}}>
							驳回
						</Button>
						<Button
							onClick={() => {
								setExamineType('拒绝')
								setIsExamineModalOpen(true)
							}}>
							拒绝
						</Button>
					</>
				) : (
					''
				)}
				{type !== 'view' && type !== 'examine' ? (
					<>
						<Button
							type="primary"
							htmlType="submit"
							loading={btnLoading}
							onClick={() => {
								onSave('save')
								setSaveType(true)
							}}>
							保存
						</Button>
						<Button
							type="primary"
							htmlType="submit"
							loading={btnLoading}
							onClick={() => {
								onSave('submit')
								setSaveType(false)
							}}>
							提交
						</Button>
						<Button
							onClick={() => {
								history.go(-1)
							}}>
							取消
						</Button>
					</>
				) : (
					<Button
						onClick={() => {
							history.go(-1)
						}}>
						返回
					</Button>
				)}
			</div>
			<Modal
				text={
					saveType
						? `确定要保存吗？请仔细核对所填信息`
						: '确定要提交吗？提交后自动保存并开始审批，请仔细核对所填信息'
				}
				onSubmit={onSubmit}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
			<Modal
				text={`确定要${examineType}吗？请仔细核对所填信息`}
				loading={btnLoading}
				onSubmit={onCompleteTask}
				isModalOpen={isExamineModalOpen}
				setIsModalOpen={setIsExamineModalOpen}
			/>
		</div>
	)
}

export default connect(({user}: any) => ({user}))(add)
